package com.zudada.servermain.security.Interceptor.Interceptor;


import com.alibaba.fastjson.JSONObject;
import com.zudada.servermain.POJO.enums.Result;
import com.zudada.servermain.POJO.enums.UserContext;
import com.zudada.servermain.security.Interceptor.Token.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@Slf4j
@Component
public class JWTCheck implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TokenUtil tokenUtil;

    @Override//目标方法执行前，返回Boolean
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //1.获取请求url
        String url = req.getRequestURI().toString();
        log.info("请求url:{}", url);
        //2判断请求url是否包含login，如果包含放行
        if (url.contains("/doc.html") ||url.contains("/login")||url.contains("/export")) {
            log.info("登录放行：{}");
            return true;
        }
        //3看请求头令牌是否存在
        String jwt1 = req.getHeader("accessToken");
        log.info("请求头令牌：{}", jwt1);
        if (!StringUtils.hasLength(jwt1)) {
            log.info("请求头为空");
            Result error = Result.error(409, "Token_is_null");
            //手懂转换jasn格式
            String s = JSONObject.toJSONString(error);
            resp.getWriter().write(s);
            return false;
        }

        //4看令牌是否出错
        try {
            Map<String, Object> claims = tokenUtil.parseJWT(jwt1);
            String id = (String) claims.get("id") ;
//
//---------------------------------------------------------------
//            //查看redis，控制只有一个登录(手机号一键登录新加)
//            String o = (String) redisTemplate.opsForValue().get("userLoginId" + id+UserEnums.MEMBER);
//            if (o == null || !jwt1.equals(o)) {
//                Result error = Result.error(409, "your_token_is_false");
//                //手懂转换jasn格式
//                String s = JSONObject.toJSONString(error);
//                resp.getWriter().write(s);
//                return false;
//            }
////-----------------------------------------------------------------------
            //将用户id存到当前线程
            UserContext.setUser(id);
            String user = UserContext.getUser();
            log.info(user + "用户ID");
            return true;
        } catch (Exception e) {
            log.info("假的令牌Jwt反问");
            Result error = Result.error(409, "your_token_is_false");
            //手懂转换jasn格式
            String s = JSONObject.toJSONString(error);
            resp.getWriter().write(s);
            return false;
        }

//        log.info("令牌合法");
//        Long id = 1849799302565265409l;
//        //由于没有登录，线程用户登录id默认为1
//        //将用户id存到当前线程
//        UserContext.setUser(id);
//        return true;
    }



    @Override//视图渲染后，最后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCOmpletion");
        // 清理用户
        UserContext.removeUser();
    }
}
